/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;
using Gtk;

namespace Whitemice.ZOGI.GtkFolios
{
  /// <summary>
  /// Provides a list of enterprises associated with the
  /// provided entity.  This only makes sense in the context
  /// of project and contact folios.
  /// </summary>
	[System.ComponentModel.Category("widget")]
	[System.ComponentModel.ToolboxItem(true)]
	public class EnterpriseTab : Gtk.ScrolledWindow, IEntityForm, IZOGIWidget
	{
		protected EnterpriseNodeView    enterprises;
		public EntityEventHandler       OnEnterpriseEdit;
		public EntityEventHandler       OnEnterpriseRemove;
		public EntityEventHandler       OnEnterpriseUnassign;
		public EventHandler             OnDataReceived;
		protected MultiResultCallback   fillCallback;
		protected int                   currentObjectId;                
	
		public EnterpriseTab()
		{
		  currentObjectId = 0;
			this.HscrollbarPolicy = PolicyType.Automatic;
			this.VscrollbarPolicy = PolicyType.Always;			
			enterprises = new EnterpriseNodeView(null, true);
			enterprises.OnEnterpriseEdit = new EntityEventHandler(EnterpriseEdit);
			enterprises.OnEnterpriseRemove = new EntityEventHandler(EnterpriseRemove);
			enterprises.OnEnterpriseUnassign = new EntityEventHandler(EnterpriseUnassign);
			fillCallback = new MultiResultCallback(this.ReceiveDataCallback);
			this.Child = enterprises;
		} // end ctor
		
		/// <summary>
		/// Clear the form
		/// </summary>
		public void Clear()
		{
			enterprises.Clear();
		} // end Clear
		 
		/// <summary>
		/// Fill the form 
		/// </summary>
		/// <param name="entity">
		/// A <see cref="Whitemice.ZOGI.Entity"/>
		/// </param>
		public void Fill(Entity entity)
		{
			IEnterpriseContainer	container;

      this.ZLOG("Fill");
			if (entity is Whitemice.ZOGI.IEnterpriseContainer)
			{
			  // we keep the objectId of the last object poured in the form
			  // so that we can verify the identify of subsequently received
			  // data from the async. server call
			  currentObjectId = entity.ObjectId;
				container = (entity as Whitemice.ZOGI.IEnterpriseContainer);
		  } else throw new Exception("Inappopriate entity type provided to form");
      this.ZLOG("Issuing fill request.");
			container.GetEnterprises(fillCallback, currentObjectId);
		} // end Fill 
		
    public void ReceiveRPCCall(RPCEventArgs args)
		{
     
      this.ZLOG("ReceiveRPCCall");
      if (args.IsError)
      {
        // TODO: Raise error message box for EnterpriseTab RPC exception
        this.ZLOG(args.Exception.Message);
        this.ZLOG(args.Exception.StackTrace);
      } else
        {
  		    // We discard received data if the context is not the objectId of the
	 	      // currently displayed enterprise.  This is because scrolling around
	 	      // in a CRUD form the data here may lag that displayed in the detail
	   	    // section and we do not want to display incorrect information.  The
		      // correct data should be received eventually. :)
          if (Convert.ToInt32(args.Context) == currentObjectId)
          {
            this.ZLOG("Filling enterprise tab with {0} enterprises", args.Payload.Count());
            enterprises.Fill(args.Payload);
          } else this.ZLOG("Discarding {0} received enterprises due to objectId mismatch", args.Payload.Count());
        }
      if (OnDataReceived != null)
        OnDataReceived(this, null);
		} // end FillCallback
		
		/// <summary>
		/// Handler for enterprise edit action
		/// </summary>
		/// <param name="_entity">
		/// A <see cref="Entity"/>
		/// </param>
		/// <param name="_context">
		/// A <see cref="System.Object"/>
		/// </param>
		/// <param name="_ex">
		/// A <see cref="Exception"/>
		/// </param>
		protected virtual void EnterpriseEdit(
		  Whitemice.ZOGI.Entity entity,
			object context, 
			Exception exception)
		{
		  if (OnEnterpriseEdit == null)
		  {
        this.ZLOG("Attempt to invoke OnEnterpriseEdit as null");
		    return;
		  } 
		  OnEnterpriseEdit(entity, context, exception); 
		} // end EnterpriseEdit
		  

    /// <summary>
    /// Handler for enterprise remove action
    /// </summary>
    /// <param name="entity">
    /// A <see cref="Whitemice.ZOGI.Entity"/>
    /// </param>
    /// <param name="context">
    /// A <see cref="System.Object"/>
    /// </param>
    /// <param name="exception">
    /// A <see cref="System.Exception"/>
    /// </param>
		protected virtual void EnterpriseRemove(
		  Whitemice.ZOGI.Entity entity,
			object context, 
			Exception exception)
		{ 
		  if (OnEnterpriseRemove == null)
		  {
        this.ZLOG("Attempt to invoke OnEnterpriseRemove as null");
		    return;
		  } 
		  OnEnterpriseRemove(entity, context, exception); 
		} // end EnterpriseRemove

    /// <summary>
    /// Handler for unassigning action.
    /// </summary>
    /// <param name="entity">
    /// A <see cref="Whitemice.ZOGI.Entity"/>
    /// </param>
    /// <param name="context">
    /// A <see cref="System.Object"/>
    /// </param>
    /// <param name="exception">
    /// A <see cref="System.Exception"/>
    /// </param>
		protected virtual void EnterpriseUnassign(
		  Whitemice.ZOGI.Entity entity,
			object context, 
			Exception exception)
		{ 
		  if (OnEnterpriseUnassign == null)
		  {
        this.ZLOG("Attempt to invoke OnEnterpriseUnassign as null");
		    return;
		  } 		
		  OnEnterpriseUnassign(entity, context, exception); 
		} // end EnterpriseUnassign
	} // end EnterpriseTab
} // end namespace